package org.cwnuit.train.utils;

import java.sql.*;

/**
 * 处理数据库连接的类
 * John@cnksi.com
 * 2011
 */
public class ConnDB {

	// 常量的设置
	public static final String DRIVER = ReadUtil.getProperty("jdbc.driverClassName");
	public static final String URL = ReadUtil.getProperty("jdbc.url");
	public static final String USER = ReadUtil.getProperty("jdbc.username");
	public static final String PASSWORD = ReadUtil.getProperty("jdbc.password");

	// 取得数据库连接；
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;

	}
	//获取Statement对象
	public static Statement getStatement(Connection conn)
	{
		Statement stmt = null;
		try {
		 stmt = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
		
	}
	
	//获取PreparedStatement对象
	public static PreparedStatement getPreparedStatement(Connection conn,String SQL)
	{
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(SQL);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
		
	}
	//获取ResultSet对象
	public static ResultSet getResultSet(Statement stmt,String sql)
	{
		ResultSet rs = null;
		
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;	
	}
	//关闭ResultSet
	public static void closeResultSet(ResultSet rs)
	{
		if(rs != null)
		{
			try {
				rs.close();
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
	}
	//关闭PreparedStatement
	public static void closePreparedStatement(PreparedStatement pstmt)
	{
		if(pstmt != null)
		{
			try {
				pstmt.close();
			} catch (SQLException e){
				e.printStackTrace();
			}
			pstmt = null;
		}
	}
	
	//关闭Statement
	public static void closeStatement(Statement stmt)
	{
		if(stmt != null)
		{
			try {
				stmt.close();
			} catch (SQLException e){
				e.printStackTrace();
			}
			stmt = null;
		}
	}
	
	//关闭Connection
	public static void closeConnection(Connection conn)
	{
		if(conn != null)
		{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}
}
